package com.gxc.net;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.junit.Test;

/**
 * @author 宫新程
 * @since 2018/12/28 4:43 PM
 */
public class Test_Net {

  @Test
  public void test1() throws UnknownHostException {

    // 获取本地主机ip对象.
    InetAddress localHost = InetAddress.getLocalHost();

    byte[] address = localHost.getAddress();
    System.out.println("getAddress()：" + new String(address, StandardCharsets.UTF_8));

    String canonicalHostName = localHost.getCanonicalHostName();
    System.out.println("getCanonicalHostName()：" + canonicalHostName);

    String hostAddress = localHost.getHostAddress();
    System.out.println("getHostAddress()：" + hostAddress); // *

    String hostName = localHost.getHostName();
    System.out.println("getHostName()：" + hostName);
  }


  @Test
  public void test2() throws UnknownHostException {
//    InetAddress ylh = InetAddress.getByName("www.baidu.com");
//    InetAddress ylh = InetAddress.getByName("192.168.137.104");
    InetAddress ylh = InetAddress.getByName("192.168.1.188");
    System.out.println("getHostAddress：" + ylh.getHostAddress());
    System.out.println("getHostName：" + ylh.getHostName());
  }

  @Test
  public void test3() throws UnknownHostException {
    InetAddress[] allByName = InetAddress.getAllByName("www.sina.com");
    Arrays.stream(allByName).forEach(e -> {
      System.out.println("getHostAddress：" + e.getHostAddress());
      System.out.println("getHostName：" + e.getHostName());
    });
  }
}
